package com.demo.interceptor;

import java.util.HashMap;
import java.util.Map;

import com.demo.constant.ErrorInfo;
import com.demo.controller.BaseController;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.JFinal;
import com.jfinal.log.Log;

public class ExceptionInterceptor implements Interceptor {

	public static final Log log = Log.getLog(ExceptionInterceptor.class);
	@Override
	public void intercept(Invocation inv) {
		BaseController controller = (BaseController) inv.getController();
//		controller.getResponse().addHeader("Access-Control-Allow-Origin","*");	// 允许所有域名访问
//		HttpServletRequest request = controller.getRequest();
//		boolean successed = false;
		try {
			inv.invoke();
		} catch (Exception e) {
			logWrite(inv, e, controller);
		}
	}
    private void logWrite(Invocation inv, Exception e, BaseController controller){
    	
        //开发模式
        if (JFinal.me().getConstants().getDevMode()){
            e.printStackTrace();
        }
		StackTraceElement stackTraceElement = e.getStackTrace()[e.getStackTrace().length-1];

        StringBuilder sb =new StringBuilder("\n---Exception Log Begin---\n");
        sb.append("Exception Controller:").append(inv.getController().getClass().getName()).append("\n");
        sb.append("Exception Method:").append(inv.getMethodName()).append("\n");
		sb.append("Exception Line:").append(stackTraceElement.getLineNumber()).append("\n");
		sb.append("Exception Type:").append(e.getClass().getName()).append("\n");
        log.info(sb.toString(),e);
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("Exception Cotroller ", inv.getController().getClass().getName());
        errorMap.put("Exception Method ", inv.getMethodName());
        errorMap.put("Exception Line ", stackTraceElement.getLineNumber());
        errorMap.put("Exception Type ", e.getClass().getName());
        controller.renderDataJson(ErrorInfo.ERR_SYS, errorMap);
    }
}
